package com.aggregate.pay.swiftpass.support;

import java.io.IOException;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aggregate.pay.swiftpass.support.utils.MD5;
import com.aggregate.pay.swiftpass.support.utils.RSA;
import com.fasterxml.jackson.core.JsonParseException;

/**
 * @author Moyq5
 * @date 2019年2月19日
 */
public class Tool {
	
	private static Logger log = LoggerFactory.getLogger(Tool.class);
	
	public static String md5Sign(FieldMap dataMap, String key) throws Exception {
		dataMap.remove("sign");
		String queryString = toQueryString(dataMap) + "&key=" + key;
		log.debug("签名内容：{}", queryString);
		String sign = MD5.MD5Encode(queryString).toUpperCase();
		log.debug("签名值：{}", sign);
		return sign;
	}
	
	public static String rsaSign(FieldMap dataMap, String priKey) throws Exception {
		dataMap.remove("sign");
		String queryString = toQueryString(dataMap);
		log.debug("签名内容：{}", queryString);
		String sign = RSA.sign(queryString.getBytes("UTF-8"), priKey);
		log.debug("签名值：{}", sign);
		return sign;
	}
	
	public static boolean rsaVerify(FieldMap dataMap, String pubKey) throws Exception {
		final String sign = dataMap.get("sign");
		dataMap.remove("sign");
		String queryString = toQueryString(dataMap);
		log.debug("签名内容：{}", queryString);
		Boolean isValid = RSA.verify(queryString.getBytes("UTF-8"), pubKey, sign);
		log.debug("签名值：{}", isValid);
		return isValid;
	}
	
	public static String toQueryString(FieldMap data) throws JsonParseException, IOException {
		StringBuffer sb = new StringBuffer();
		for(Map.Entry<String, String> entry : data.entrySet()) {
			if (null != entry.getValue() && !entry.getValue().isEmpty()) {
				sb.append(entry.getKey());
				sb.append("=");
				sb.append(entry.getValue());
				sb.append("&");
			}
		}
		if (sb.length() > 0) {
			sb.delete(sb.length()-1, sb.length());// 去掉最后的“&”
		}
		log.debug("组装结果：{}", sb.toString());
		return sb.toString();
	}
	
}